#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class Solution {
	int power = 0;
	vector<vector<int>> stjump;
	vector<vector<long long>> stsum;

    public:
	long long getMaxFunctionValue(vector<int> &receiver, long long k)
	{
		int n = receiver.size();
		power = log2(k);

		stjump.resize(n, vector<int>(power + 1, 0));
		stsum.resize(n, vector<long long>(power + 1, 0));

		for (int i = 0; i < n; i++) {
			stjump[i][0] = receiver[i];
			stsum[i][0] = receiver[i];
		}

		for (int p = 1; p <= power; p++) {
			for (int i = 0; i < n; i++) {
				stjump[i][p] = stjump[stjump[i][p - 1]][p - 1];
				stsum[i][p] = stsum[i][p - 1] + stsum[stjump[i][p - 1]][p - 1];
			}
		}

		long long maxsum = 0, isum = 0, steps = k;
		for (int i = 0, cur = i; i < n; i++) {
			isum = i;
                        cur = i;
                        k = steps;
                        int p = 0;
                        while(k){
                                if(k & 1){
                                        isum += stsum[cur][p];
                                        cur = stjump[cur][p];
                                }
                                k >>= 1;
                                p++;

                        }
			maxsum = max(maxsum, isum);
		}

		return maxsum;
	}
};

int main()
{
	vector<int> receiver = {1,1,1,2,3};
	int k = 3;
	cout << Solution().getMaxFunctionValue(receiver, k) << endl;
	return 0;
}